package com.yupi.yupicturebackend.api.imageSearch.sub;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.yupicturebackend.api.imageSearch.model.ImageSearchResult;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class GetImageListApi {
    public static void main(String[] args) {
        String imageUrl = "https://graph.baidu.com/ajax/pcsimi?carousel=503&entrance=GENERAL&extUiData%5BisLogoShow%5D=1&inspire=general_pc&limit=30&next=2&render_type=card&session_id=1462102440230947431&sign=121c3e97cd54acd88139901749360154&tk=4fd9b&tpl_from=pc";
        List<ImageSearchResult> imageList = getImageList(imageUrl);
        System.out.println(imageList);
    }

    public static List<ImageSearchResult> getImageList(String imageUrl) {
        try {
            // 发起 get请求
            HttpResponse response = HttpUtil.createGet(imageUrl).execute();
            // 获取相应内容
            int statusCode = response.getStatus();
            String body = response.body();
            if (statusCode == 200) {
                return processResponse(body);
            } else {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "百度以图搜图接口调用失败");
            }
        } catch (Exception e) {
            log.error("百度以图搜图接口调用异常:{}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "百度以图搜图接口调用异常");
        }
    }

    public static List<ImageSearchResult> processResponse(String responseBody) {
        JSONObject jsonObject = new JSONObject(responseBody);
        if (!jsonObject.containsKey("data")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未获取到图片列表");
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (!data.containsKey("list")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未获取到图片列表");
        }
        JSONArray list = data.getJSONArray("list");
        return JSONUtil.toList(list, ImageSearchResult.class);
    }
}
